import QtQuick
import QtQuick.Controls
import QtQuick.Layouts
import "qrc:/qml/styles" as Styles
import "qrc:/qml/components"

Rectangle {
    id: autoDoorTab
    color: "transparent"

    property var doorModel: GlobalResourceViewModel ? GlobalResourceViewModel.autoDoorListModel : null
    property var filteredDoors: []

    onDoorModelChanged: rebuildDoorList()

    function rebuildDoorList() {
        const results = [];
        if (doorModel) {
            for (let i = 0; i < doorModel.rowCount(); i++) {
                const door = doorModel.getDoorData(i);
                if (door) {
                    results.push(door);
                }
            }
        }
        filteredDoors = results;
    }

    Connections {
        target: doorModel
        ignoreUnknownSignals: true
        function onModelReset() { rebuildDoorList(); }
        function onRowsInserted() { rebuildDoorList(); }
        function onRowsRemoved() { rebuildDoorList(); }
        function onDataChanged() { rebuildDoorList(); }
    }

    Component.onCompleted: rebuildDoorList()

    ColumnLayout {
        anchors.fill: parent
        anchors.margins: Styles.Theme.spacingLarge
        spacing: Styles.Theme.spacingLarge

        // 顶部统计
        RowLayout {
            Layout.fillWidth: true
            spacing: Styles.Theme.spacingNormal

            KpiCard {
                width: 200
                height: 100
                title: "自动门总数"
                value: GlobalResourceViewModel ? GlobalResourceViewModel.totalAutoDoorCount : 0
                iconSource: "🚪"
                accentColor: Styles.Theme.primary
                enableValueAnimation: false
            }

            KpiCard {
                width: 200
                height: 100
                title: "在线设备"
                value: GlobalResourceViewModel ? GlobalResourceViewModel.onlineAutoDoorCount : 0
                iconSource: "✓"
                accentColor: Styles.Theme.success
                enableValueAnimation: false
            }

            KpiCard {
                width: 200
                height: 100
                title: "离线设备"
                value: {
                    if (!GlobalResourceViewModel) return 0;
                    return Math.max(0, GlobalResourceViewModel.totalAutoDoorCount - GlobalResourceViewModel.onlineAutoDoorCount);
                }
                iconSource: "⚠"
                accentColor: Styles.Theme.warning
                enableValueAnimation: false
            }
        }

        Rectangle {
            Layout.fillWidth: true
            Layout.fillHeight: true
            color: Styles.Theme.surface
            radius: Styles.Theme.radiusNormal

            ColumnLayout {
                anchors.fill: parent
                anchors.margins: Styles.Theme.spacingNormal
                spacing: Styles.Theme.spacingNormal

                RowLayout {
                    Layout.fillWidth: true

                    Text {
                        text: "自动门列表"
                        font.pixelSize: Styles.Theme.fontSizeLarge
                        font.weight: Styles.Theme.fontWeightBold
                        color: Styles.Theme.textPrimary
                    }

                    Item { Layout.fillWidth: true }

                    ActionButton {
                        text: "刷新"
                        iconSource: "qrc:/icons/refresh.svg"
                        size: "small"
                        onClicked: {
                            if (GlobalResourceViewModel) {
                                GlobalResourceViewModel.refreshAutoDoorData();
                            }
                        }
                    }
                }

                Rectangle {
                    Layout.fillWidth: true
                    height: 40
                    color: Styles.Theme.surfaceHeader
                    radius: Styles.Theme.radiusSmall

                    Row {
                        anchors.fill: parent
                        anchors.leftMargin: Styles.Theme.spacingNormal
                        anchors.rightMargin: Styles.Theme.spacingNormal
                        spacing: Styles.Theme.spacingNormal

                        Text { width: 100; text: "门编号"; font.pixelSize: Styles.Theme.fontSizeNormal; font.weight: Styles.Theme.fontWeightMedium; color: Styles.Theme.textSecondary; anchors.verticalCenter: parent.verticalCenter }
                        Text { width: 80; text: "楼层"; font.pixelSize: Styles.Theme.fontSizeNormal; font.weight: Styles.Theme.fontWeightMedium; color: Styles.Theme.textSecondary; anchors.verticalCenter: parent.verticalCenter }
                        Text { width: 150; text: "设备ID"; font.pixelSize: Styles.Theme.fontSizeNormal; font.weight: Styles.Theme.fontWeightMedium; color: Styles.Theme.textSecondary; anchors.verticalCenter: parent.verticalCenter }
                        Text { width: 200; text: "点位范围"; font.pixelSize: Styles.Theme.fontSizeNormal; font.weight: Styles.Theme.fontWeightMedium; color: Styles.Theme.textSecondary; anchors.verticalCenter: parent.verticalCenter }
                        Text { width: 120; text: "门状态"; font.pixelSize: Styles.Theme.fontSizeNormal; font.weight: Styles.Theme.fontWeightMedium; color: Styles.Theme.textSecondary; anchors.verticalCenter: parent.verticalCenter }
                        Text { width: 120; text: "设备状态"; font.pixelSize: Styles.Theme.fontSizeNormal; font.weight: Styles.Theme.fontWeightMedium; color: Styles.Theme.textSecondary; anchors.verticalCenter: parent.verticalCenter }
                        Text { width: 200; text: "控制"; font.pixelSize: Styles.Theme.fontSizeNormal; font.weight: Styles.Theme.fontWeightMedium; color: Styles.Theme.textSecondary; anchors.verticalCenter: parent.verticalCenter }
                    }
                }

                Item {
                    Layout.fillWidth: true
                    Layout.fillHeight: true

                    ListView {
                        id: doorListView
                        anchors.fill: parent
                        clip: true
                        spacing: 0
                        boundsBehavior: Flickable.StopAtBounds
                        highlightMoveDuration: 0
                        model: filteredDoors

                        delegate: Rectangle {
                            id: doorListItem
                            required property var modelData
                            required property int index
                            readonly property var door: modelData || ({})
                            readonly property string stateText: {
                                if (door.state === undefined || door.state === null) {
                                    return "";
                                }
                                return String(door.state);
                            }
                            width: doorListView.width
                            height: 60
                            radius: Styles.Theme.radiusSmall
                            color: index % 2 === 0 ? Styles.Theme.surface : Styles.Theme.backgroundAlternate

                            // 平滑的颜色过渡
                            Behavior on color {
                                ColorAnimation { duration: Styles.Theme.animationFast }
                            }

                            RowLayout {
                                anchors.fill: parent
                                anchors.leftMargin: Styles.Theme.spacingNormal
                                anchors.rightMargin: Styles.Theme.spacingNormal
                                spacing: Styles.Theme.spacingNormal

                                Text {
                                    Layout.preferredWidth: 100
                                    Layout.alignment: Qt.AlignVCenter
                                    text: door.doorId !== undefined
                                          ? "门 " + door.doorId
                                          : "-"
                                    font.pixelSize: Styles.Theme.fontSizeNormal
                                    font.weight: Styles.Theme.fontWeightMedium
                                    color: Styles.Theme.textPrimary
                                }

                                Text {
                                    Layout.preferredWidth: 80
                                    Layout.alignment: Qt.AlignVCenter
                                    text: door.floor >= 0 ? door.floor + "F" : "-"
                                    font.pixelSize: Styles.Theme.fontSizeNormal
                                    color: Styles.Theme.textPrimary
                                }

                                Text {
                                    Layout.preferredWidth: 150
                                    Layout.alignment: Qt.AlignVCenter
                                    text: door.deviceId !== undefined
                                          ? "0x" + door.deviceId.toString(16).toUpperCase()
                                          : "-"
                                    font.pixelSize: Styles.Theme.fontSizeNormal
                                    color: Styles.Theme.textSecondary
                                }

                                Text {
                                    Layout.preferredWidth: 200
                                    Layout.alignment: Qt.AlignVCenter
                                    text: (door.point1 || "-") + " → " + (door.point2 || "-")
                                    font.pixelSize: Styles.Theme.fontSizeNormal
                                    color: Styles.Theme.textPrimary
                                    elide: Text.ElideRight
                                }

                                StatusIndicator {
                                    Layout.preferredWidth: 120
                                    Layout.alignment: Qt.AlignVCenter
                                    label: stateText
                                    animated: false
                                    status: {
                                        const doorState = stateText;
                                        if (doorState.indexOf("打开") >= 0) return "success";
                                        if (doorState.indexOf("关闭") >= 0) return "normal";
                                        return "warning";
                                    }
                                    size: "small"
                                    showIndicator: true
                                }

                                RowLayout {
                                    Layout.preferredWidth: 120
                                    Layout.alignment: Qt.AlignVCenter
                                    spacing: Styles.Theme.spacingXSmall

                                    Rectangle {
                                        width: 8
                                        height: 8
                                        radius: 4
                                        Layout.alignment: Qt.AlignVCenter
                                        color: door.isOnline ? Styles.Theme.success : Styles.Theme.danger
                                    }

                                    Text {
                                        Layout.alignment: Qt.AlignVCenter
                                        text: door.isOnline ? "在线" : "离线"
                                        font.pixelSize: Styles.Theme.fontSizeSmall
                                        color: door.isOnline ? Styles.Theme.success : Styles.Theme.danger
                                    }
                                }

                                Item {
                                    Layout.fillWidth: true
                                }

                                RowLayout {
                                    Layout.preferredWidth: 200
                                    Layout.alignment: Qt.AlignVCenter
                                    spacing: Styles.Theme.spacingSmall

                                    ActionButton {
                                        Layout.preferredWidth: 90
                                        text: "开门"
                                        size: "small"
                                        buttonType: "primary"
                                         enabled: door.isOnline
                                         onClicked: {
                                             if (GlobalResourceViewModel) {
                                                 GlobalResourceViewModel.openAutoDoor(door.doorId);
                                             }
                                         }
                                    }

                                    ActionButton {
                                        Layout.preferredWidth: 90
                                        text: "关门"
                                        size: "small"
                                        buttonType: "secondary"
                                         enabled: door.isOnline
                                         onClicked: {
                                             if (GlobalResourceViewModel) {
                                                 GlobalResourceViewModel.closeAutoDoor(door.doorId);
                                             }
                                         }
                                    }
                                }
                            }

                            MouseArea {
                                anchors.fill: parent
                                hoverEnabled: true
                                propagateComposedEvents: true
                                onEntered: doorListItem.color = Styles.Theme.surfaceVariant
                                onExited: doorListItem.color = index % 2 === 0 ? Styles.Theme.surface : Styles.Theme.backgroundAlternate
                                onPressed: function(mouse) { mouse.accepted = false; }
                                onClicked: function(mouse) { mouse.accepted = false; }
                            }
                        }

                        ScrollBar.vertical: ScrollBar {
                            policy: ScrollBar.AsNeeded
                        }
                    }

                    Item {
                        id: doorEmptyState
                        anchors.fill: parent
                        visible: filteredDoors.length === 0

                        Column {
                            anchors.centerIn: parent
                            spacing: Styles.Theme.spacingSmall
                            opacity: 0.8

                            Text {
                                text: "暂无自动门数据"
                                font.pixelSize: Styles.Theme.fontSizeLarge
                                font.weight: Styles.Theme.fontWeightBold
                                color: Styles.Theme.textSecondary
                                horizontalAlignment: Text.AlignHCenter
                            }

                            Text {
                                text: "请检查配置或点击刷新按钮"
                                font.pixelSize: Styles.Theme.fontSizeNormal
                                color: Styles.Theme.textSecondary
                                horizontalAlignment: Text.AlignHCenter
                            }
                        }
                    }
                }
            }
        }
    }
}
